﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NHibernate;
using NHibernate.Criterion;
using Revis.VClinicNet.Core.Domain.Credentials;
using Revis.VClinicNet.Core.Domain.Repository;

namespace Revis.VClinicNet.Core.Domain.Persistence.Nh
{
    public class WorkerUserRepository : RepositoryBase<WorkerUser>, IWorkerUserRepository
    {
        public WorkerUserRepository(ISessionFactory factory)
            : base(factory)
        {
        }

        public WorkerUser Find(string login, string hashedPassword)
        {
            return Session.CreateCriteria<WorkerUser>("wu")
                .Add(Expression.Eq("wu.Login", login))
                .Add(Expression.Eq("wu.Password", hashedPassword))
                .Add(Expression.Eq("wu.IsActive", true))
                .UniqueResult<WorkerUser>();
        }

        public WorkerUser Find(string login)
        {
            return Session.CreateCriteria<WorkerUser>("wu")
                .Add(Expression.Eq("wu.Login", login))
                .UniqueResult<WorkerUser>();
        }

        public override IList<WorkerUser> FindBy(string field, string value)
        {
            IList<WorkerUser> finded = null;
            try {
                finded = Session.CreateCriteria<WorkerUser>()
                    .CreateAlias("RelatedWorker", "Worker")
                    .Add(Expression.Like(field, value, MatchMode.Anywhere)).List<WorkerUser>();
            } catch (QueryException) {
                finded = null;
            }
            return finded;
        }

        public IList<WorkerUser> FindBy(string field, string value, bool activity)
        {
            IList<WorkerUser> finded = null;
            try {
                finded = Session.CreateCriteria<WorkerUser>()
                    .CreateAlias("RelatedWorker", "Worker")
                    .Add(Expression.Like(field, value, MatchMode.Anywhere))
                    .Add(Expression.Eq("IsActive", activity))
                    .List<WorkerUser>();
            } catch (QueryException) {
                finded = null;
            }
            return finded;
        }

        //public WorkerUser FindWorker(long workerId)
        //{
        //    WorkerUser workerUser = Session.CreateCriteria<WorkerUser>("wu")
        //        .SetFetchMode("RelatedWorker", FetchMode.Eager)
        //        .Add(Expression.Eq("wu.RelatedWorker.Id", workerId))
        //        .UniqueResult<WorkerUser>();
        //    return workerUser;
        //}



    }
}
